/******************************************************************************
 * Copyright (C) 671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef NODECPP_FOUNDATION_MUTEX_POSIX_H_
#define NODECPP_FOUNDATION_MUTEX_POSIX_H_

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif

#include <stdexcept>
#include <pthread.h>
#include <NodeCpp/Macros.h>

namespace NodeCpp
{
	class MutexImpl
    {
    public:
        MutexImpl(void);
        ~MutexImpl(void) { pthread_mutex_destroy(&Mutex_); }

        void LockImpl(void) {
            NODECPP_COND_THROW(pthread_mutex_lock(&Mutex_) != 0,
                	std::runtime_error("Failed lock mutex."));
        }

        bool TryLockImpl(void) {
            return (pthread_mutex_trylock(&Mutex_) == 0);
        }

        void UnlockImpl(void) {
            NODECPP_COND_THROW(pthread_mutex_unlock(&Mutex_) != 0,
            		std::runtime_error("Failed unlock mutex."));
        }

    private:
        pthread_mutex_t Mutex_;
    };
}

#endif // NODECPP_FOUNDATION_MUTEX_POSIX_H_
